package com.zzy.demo.utils;

import javax.servlet.http.HttpServletRequest;

import com.zzy.tools.string.StringsUtil;

/**
 * ip工具类
 *
 * @author weiyuan
 * @date 20231226
 */
public class IpUtils {
    private static final String STATUS_UNKNOWN = "unknown";
    private static final Integer IP_LENGTH = 15;
    public static final String LOCAL_NOT_IP = "0:0:0:0:0:0:0:1";
    public static final String LOCAL_IP = "127.0.0.1";
    public static final String REQUEST_HEADER_X_REAL_IP = "X-Real-IP";
    public static final String REQUEST_HEADER_X_FORWARDED_FOR = "X-Forwarded-For";
    public static final String REQUEST_HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";
    public static final String REQUEST_HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
    public static final String REQUEST_HEADER_HTTP_CLIENT_IP = "HTTP_CLIENT_IP";
    public static final String REQUEST_HEADER_HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR";

    public IpUtils() {
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader(REQUEST_HEADER_X_REAL_IP);
        if (StringsUtil.hasText(ip) && !STATUS_UNKNOWN.equalsIgnoreCase(ip)) {
            return ip;
        } else {
            ip = request.getHeader(REQUEST_HEADER_X_FORWARDED_FOR);
            if (ip != null && ip.length() != 0 && !STATUS_UNKNOWN.equalsIgnoreCase(ip)) {
                if (ip.length() > IP_LENGTH) {
                    String[] ips = ip.split(",");

                    for (int index = 0; index < ips.length; ++index) {
                        String strIp = ips[index];
                        if (!STATUS_UNKNOWN.equalsIgnoreCase(strIp)) {
                            ip = strIp;
                            break;
                        }
                    }
                }
            } else {
                if (ip == null || ip.length() == 0 || STATUS_UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader(REQUEST_HEADER_PROXY_CLIENT_IP);
                }

                if (ip == null || ip.length() == 0 || STATUS_UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader(REQUEST_HEADER_WL_PROXY_CLIENT_IP);
                }

                if (ip == null || ip.length() == 0 || STATUS_UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader(REQUEST_HEADER_HTTP_CLIENT_IP);
                }

                if (ip == null || ip.length() == 0 || STATUS_UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader(REQUEST_HEADER_HTTP_X_FORWARDED_FOR);
                }

                if (ip == null || ip.length() == 0 || STATUS_UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
            }

            return ip;
        }
    }
}